package com.ljp.chat.exception;

import cn.hutool.json.JSONUtil;
import com.ljp.chat.entity.Result;
import com.ljp.chat.entity.enums.ResultEnum;
import com.ljp.chat.support.expansion.exception.UniqueException;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.lang.reflect.Method;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestControllerAdvice
public class GlobalExceptionAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        Method method = returnType.getMethod();
        return null != method && Void.class != method.getReturnType();
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (body == null) {
            //当 body 返回类型为 string 并且为null会出现 java.lang.ClassCastException: Result cannot be cast to java.lang.String,则封装ResultMsg对象并转换为String返回*/
            if (methodParameter.getParameterType().getName().equals("java.lang.String")) {
                return JSONUtil.toJsonStr(new Result<>().Result(ResultEnum.SUCCESS));
            }
            return new Result<>().Result(ResultEnum.SUCCESS);
        }
        //当 body Result(统一封装返回对象),则直接返回
        if (body instanceof Result) {
            return body;
        }
        ///当 o 为string 则特殊处理 java.lang.ClassCastException: Result cannot be cast to java.lang.String,封装ResultMsg对象并转换为String返回
        return JSONUtil.toJsonStr(new Result<>().SUCCESS(body));
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> exceptionDeal(Exception e) {
        Result<Object> result = new Result<>().Result(ResultEnum.FAILED);
        if (e instanceof NullPointerException) {
            result.setMsg("程序异常-空指针异常");
            e.printStackTrace();
        } else if (e instanceof WarnException) {
            result.setMsg(e.getMessage());
        } else if (e instanceof UniqueException) {
            result.setMsg(e.getMessage());
        } else if (e instanceof MethodArgumentNotValidException) {
            result.setMsg(getMsgByMethodArgumentNotValidException(e));
        } else if (e instanceof MissingServletRequestParameterException){
            result.setMsg("缺少必填参数");
        }else {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * Get msg by method argument not valid exception string.
     * 从异常中提取信息
     *
     * @param e the e
     * @return the string
     */
    private String getMsgByMethodArgumentNotValidException(Exception e) {
        String pattern = "\\[[-\\w\\u4e00-\\u9fa5]*]]\\s*$";
        Pattern compile = Pattern.compile(pattern);
        Matcher m = compile.matcher(e.getMessage());
        if (m.find()) {
            String msg = m.group();
            return msg.substring(1, msg.length() - 3);
        }
        return null;
    }

}
